---
category: Level 1 — Basic
created: '2020-02-28'
keywords:
title: Toggle password visibility
---

Assume that we have two elements. A password element, and a button for toggling the visibility of the password:

```html
<input type="password" id="password" />

<button id="toggle">Toggle</button>
```

In order to show the password, we turn the password element to an usual textbox whose `type` attribute is `text`:

```js
// Query the elements
const passwordEle = document.getElementById('password');
const toggleEle = document.getElementById('toggle');

toggleEle.addEventListener('click', function () {
    const type = passwordEle.getAttribute('type');

    passwordEle.setAttribute(
        'type',
        // Switch it to a text field if it's a password field
        // currently, and vice versa
        type === 'password' ? 'text' : 'password'
    );
});
```

## Demo

<Playground>
```html
<div style="margin: 4rem auto; width: 16rem">
    <div class="toggle">
        <input type="password" class="toggle__input" autocomplete="off" id="password" />

        <button class="toggle__button" id="toggle">
            <svg
                viewBox="0 0 24 24"
                style="
                    fill: none;
                    height: 24px;
                    stroke: rgba(0, 0, 0, 0.4);
                    stroke-linecap: round;
                    stroke-linejoin: round;
                    stroke-width: 1;
                    width: 24px;
                "
            >
                <path
                    d="M23.5,12c0,0-5.148,6.5-11.5,6.5S0.5,12,0.5,12S5.648,5.5,12,5.5S23.5,12,23.5,12z M12,8c2.209,0,4,1.791,4,4 s-1.791,4-4,4s-4-1.791-4-4S9.791,8,12,8z M12,10c1.105,0,2,0.895,2,2s-0.895,2-2,2s-2-0.895-2-2"
                />
            </svg>
        </button>
    </div>
</div>
```

```css
.toggle {
    align-items: center;
    display: flex;
    border: 1px solid #cbd5e0;
}
.toggle__input {
    border: none;
    flex: 1;

    /* Misc */
    padding: 0.5rem;

}
.toggle__button {
    background-color: transparent;
    border: none;
    cursor: pointer;
    padding: 0.5rem;
}
```

```js
document.addEventListener('DOMContentLoaded', function () {
    const passwordEle = document.getElementById('password');
    const toggleEle = document.getElementById('toggle');

    toggleEle.addEventListener('click', function () {
        const type = passwordEle.getAttribute('type');
        passwordEle.setAttribute('type', type === 'password' ? 'text' : 'password');
    });
});
```
</Playground>

## See also

-   [Attach or detach an event handler](https://phuoc.ng/collection/html-dom/attach-or-detach-an-event-handler/)
-   [Get set and remove attributes](https://phuoc.ng/collection/html-dom/get-set-and-remove-attributes/)
